package com.example.websoketclient.client.impl;

import com.example.websoketclient.client.Client;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author ZhenWuWang
 */
public class DefaultWebSocketClient implements Client
{
    public WebSocketClient webSocketClient;

    private String url = "ws://localhost:8080/websocket/socketServer.do?userName=rwby";

    @Override
    public void start()
    {
        try
        {
            webSocketClient = new WebSocketClient(new URI(url), new Draft_6455())
            {
                @Override
                public void onOpen(ServerHandshake serverHandshake)
                {
                    System.out.println("握手成功");
                }

                @Override
                public void onMessage(String msg)
                {
                    System.out.println("收到消息==========" + msg);
                    if (msg.equals("over"))
                    {
                        webSocketClient.close();
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b)
                {
                    System.out.println("链接已关闭");
                }

                @Override
                public void onError(Exception e)
                {
                    e.printStackTrace();
                    System.out.println("发生错误已关闭");
                }
            };
        } catch (URISyntaxException e)
        {
            e.printStackTrace();
        }
        webSocketClient.connect();
        System.out.println(webSocketClient.getDraft());
        while (!webSocketClient.getReadyState().equals(WebSocket.READYSTATE.OPEN))
        {
            System.out.println("正在连接...");
        }
        //连接成功,发送信息
        webSocketClient.send("哈喽,连接一下啊");
    }
}
